package com.xjrsoft.module.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.core.secure.XjrUser;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.base.entity.XjrBaseUser;
import com.xjrsoft.module.base.service.*;
import com.xjrsoft.module.base.utils.OrganizationCacheUtil;
import com.xjrsoft.module.workflow.dto.GetPageListNwfRelationDto;
import com.xjrsoft.module.workflow.dto.NwfRelationDto;
import com.xjrsoft.module.workflow.entity.XjrNwfRelation;
import com.xjrsoft.module.workflow.entity.XjrNwfSchemeauth;
import com.xjrsoft.module.workflow.service.IXjrNwfRelationService;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeAuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

@AllArgsConstructor
@ControllerAdvice
@RestController
@RequestMapping("/workflow-relation")
@Api(value = "工作流关联控制器", tags = "工作流关联控制器")
public class NwfRelationController {

    IXjrNwfRelationService xjrnwfrelationService;

    IXjrBaseUserService userService;

    IXjrNwfSchemeAuthService nwfSchemeInfoAuthService;

    IXjrBasePostService postService;

    IXjrBaseRoleService roleService;

    IXjrBaseDepartmentService departmentService;

    IXjrBaseCompanyService companyService;

    IXjrBaseUserRelationService userRelationService;

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月14日
     * @url: /queryNwfRelation
     * @description:查询专项菜单列表
     */
    @GetMapping
    @ApiOperation(value = "查询流程关联接口")
    public Response queryNwfRelation(GetPageListNwfRelationDto dto) {
        return Response.ok(xjrnwfrelationService.queryNwfRelation(dto));
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月14日
     * @url: /addNwfRelation
     * @description:新增专项菜单
     */
    @PostMapping
    @ApiOperation(value = "新增专项菜单")
    public Response addNwfRelation(@RequestBody NwfRelationDto dto) {
        // 获取当前的登录用户
        XjrUser currentUser = SecureUtil.getUser();
        return Response.ok(xjrnwfrelationService.addNwfRelation(dto, currentUser));
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月14日
     * @url: /addNwfRelation
     * @description:更新专项菜单
     */
    @SneakyThrows
    @PutMapping("/{id}")
    @ApiOperation(value = "更新专项菜单")
    @ApiImplicitParam(name = "id", dataType = "string", paramType = "query",value = "关联id")
    public Response updateNwfRelation(@PathVariable String id, @RequestBody NwfRelationDto dto) {
        // 获取当前的登录用户
        XjrUser currentUser = SecureUtil.getUser();
        return Response.status(xjrnwfrelationService.updateNwfRelation(id, dto, currentUser));
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月14日
     * @url: /deleteNwfRelation
     * @description:删除专项菜单
     */
    @SneakyThrows
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除专项菜单")
    @ApiImplicitParam(name = "id", dataType = "string", paramType = "query",value = "关联id")
    public Response deleteNwfRelation(@PathVariable("id") String id) {
        return Response.status(xjrnwfrelationService.deleteNwfRelation(id));
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月15日
     * @url: /getNwfFormInfo
     * @description: 根据nwfschemeInfoId获取表单信息
     */
    @GetMapping("/formInfo")
    @ApiOperation(value = "根据nwfschemeInfoId获取表单信息")
    @ApiImplicitParam(name = "nwfSchemeInfoId", dataType = "string", paramType = "query",value = "流程模板id")
    public Response getNwfFormInfo(String nwfSchemeInfoId) {
        return Response.ok(xjrnwfrelationService.getNwfFormInfo(nwfSchemeInfoId));
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月15日
     * @url: /getNwfFormInfo
     * @description: 根据nwfschemeInfoId获取
     */
    @GetMapping("/tableField")
    @ApiImplicitParam(name = "nwfSchemeInfoId", dataType = "string", paramType = "query",value = "流程模板id")
    public Response getTableField(String nwfSchemeInfoId) {
        return Response.ok(xjrnwfrelationService.getTableFieldList(nwfSchemeInfoId));
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月17日
     * @url: /getNwfRelationInfoById
     * @description:根据主键Id获取nwfrelationInfo
     */
    @GetMapping("/info/{id}")
    @ApiImplicitParam(name = "id", dataType = "string", paramType = "query",value = "关联id")
    public Response getNwfRelationInfoById(String id) {
        XjrNwfRelation xjrNwfRelation = xjrnwfrelationService.getById(id);
        List<XjrBaseUser> xjrBaseUserList = OrganizationCacheUtil.getListCaches(OrganizationCacheUtil.USER_LIST_CACHE_KEY);
        if (xjrNwfRelation != null) {
            JSONObject settingJson = JSON.parseObject(xjrNwfRelation.getSettingJson());
            JSONObject step4 = settingJson.getJSONObject("step4");
            JSONArray step5 = settingJson.getJSONArray("step5");
            if(step4!=null&&step5!=null) {
                JSONArray fields = step4.getJSONArray("fields");
                boolean fieldAuthority = xjrnwfrelationService.checkFieldAuthority(id, SecureUtil.getUserId(), xjrBaseUserList);
                if (!fieldAuthority) {
                    JSONArray formFields = xjrnwfrelationService.getFormFieldById(id);
                    for (int i = 0; i < formFields.size(); i++) {
                        JSONObject formFieldObj = formFields.getJSONObject(i);
                        Iterator<Object> fieldsIterator = fields.iterator();
                        Iterator<Object> step5Iterator = step5.iterator();
                        while (fieldsIterator.hasNext()) {
                            JSONObject fieldObj = (JSONObject) fieldsIterator.next();
                            if (StringUtil.equals(formFieldObj.getString("name"), fieldObj.getString("name"))) {
                                fieldsIterator.remove();
                                break;
                            }
                        }
                        while (step5Iterator.hasNext()) {
                            JSONObject step5Obj = (JSONObject) step5Iterator.next();
                            if (StringUtil.equals(formFieldObj.getString("name"), step5Obj.getString("name"))) {
                                step5Iterator.remove();
                                break;
                            }
                        }
                    }
                }
            }
            return Response.ok(settingJson);
        }
        return Response.notOk("未找到该条数据!");
    }

    /**
     * @author 湘北智造-框架开发组
     * @date:2020年7月23日
     * @url: /getNwfSchemeInfoAuthority
     * @description:获取模板的权限人员
     */

    public Response getNwfSchemeInfoAuthority(String fId) {
        JSONArray jsonArray = new JSONArray();
        List<XjrNwfSchemeauth> xjrNwfSchemeAuthList = nwfSchemeInfoAuthService.getBySchemeInfoId(fId);
        for (XjrNwfSchemeauth xjrNwfSchemeauth : xjrNwfSchemeAuthList) {
            JSONObject jsonObject = new JSONObject();
            // 1岗位2角色3用户4所用人可看
            Integer fObjtype = xjrNwfSchemeauth.getObjType();
            String fObjid = xjrNwfSchemeauth.getObjId();
            String fObjname = xjrNwfSchemeauth.getObjName();
            jsonObject.put("F_Id", StringUtil.randomUUID());
            jsonObject.put("F_ObjId", fObjid);
            jsonObject.put("F_ObjName", fObjname);
            jsonObject.put("F_ObjType", fObjtype);
            jsonArray.add(jsonObject);
        }
        return Response.ok(jsonArray);
    }
}


